﻿using System;
using System.Text;
using EP.Base.BaseService.Manager.Interface.Business;
using EP.Base.BaseService.Manager.Interface.Common;
using EP.Base.BaseService.Manager.Interface.Data;
using EP.Base.BaseService.Manager.Model;
using EP.Base.BaseService.Manager.Model.Entity;

namespace EP.Base.BaseService.Manager.Business.Task
{
    /// <summary>
    /// 删除索引时确认提醒任务
    /// </summary>
    public class DlIndexConfirmRemindTask : IEsIndexHandelTask
    {

        private readonly IIndexDeleteLogs _indexDeleteLogs;
        private readonly IEmail _email;
        private readonly IJson _json;
        private readonly ILog _log;

        public DlIndexConfirmRemindTask(IIndexDeleteLogs indexDeleteLogs, IEmail email, IJson json, ILog log)
        {
            _indexDeleteLogs = indexDeleteLogs;
            _email = email;
            _json = json;
            _log = log;
        }

        public bool Exec(EsTaskConfig taskConfig)
        {
            var currentTaskConfig = _json.DeserializeObject<DlIndexConfirmRemindTaskConfig>(taskConfig.Configs);
            //获取待确认记录
            var logs = _indexDeleteLogs.GetByIndexConfigId(taskConfig.IndexConfigId, (short)Config.Enum.EnumIndexDeleteLogState.WaitConfirmation);
            if (logs != null && logs.Count > 0)
            {
                var sb=new StringBuilder();
                sb.Append("您有以下索引被检测出需要删除，请您及时确认！<br/>");
                foreach (var indexDeleteLog in logs)
                {
                    sb.AppendFormat("index={0},time={1}", indexDeleteLog.IndexName, indexDeleteLog.IndexCreateTime);
                    sb.Append("<br/>");
                }
                sb.AppendFormat("发送时间-{0}", DateTime.Now);
                //发送提醒邮件
                _email.Send(sb.ToString(), "ES索引待删除确认提示", currentTaskConfig.EmailAddress.Split(','));
                var result= _indexDeleteLogs.UpdateStateByIndexConfigId(taskConfig.IndexConfigId,
                    (short) Config.Enum.EnumIndexDeleteLogState.WaitConfirmation,
                    (short) Config.Enum.EnumIndexDeleteLogState.Confirmation);
                _log.DebugFormat("提醒任务taskConfigId={0}执行完毕;dbResult={1}",taskConfig.Id, result);
            }
            return true;
        }
    }
}
